package com.company.cloud.mall.modules.mgr.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

import com.company.cloud.common.auth.annotation.StaffLogc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.YNEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.log.annotation.SysLog;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.mall.constant.MallErrorEnum;
import com.company.cloud.mall.modules.api.response.OrderModel;
import com.company.cloud.mall.modules.api.response.OrderReturnsModel;
import com.company.cloud.mall.modules.app.controller.req.OrderReturnsCheckParam;
import com.company.cloud.mall.modules.app.controller.req.OrderReturnsReceiveParam;
import com.company.cloud.mall.modules.app.controller.req.OrderReturnsRefundParam;
import com.company.cloud.mall.modules.app.service.ShopAfterSaleReturnsService;
import com.company.cloud.mall.modules.app.service.ShopOrderService;
import com.company.cloud.mall.modules.base.entity.OrderLog;
import com.company.cloud.mall.modules.base.entity.OrderReturns;
import com.company.cloud.mall.modules.base.service.OrderLogService;
import com.company.cloud.mall.modules.base.service.OrderReturnsService;
import com.company.cloud.mall.modules.mgr.controller.req.OrderReturnMgrQuery4PageParam;
import com.company.cloud.mall.modules.utils.ShopOrderConvertUtils;
import com.company.cloud.user.modules.api.response.UserSimple;
import com.company.cloud.user.modules.api.service.UserRemoteService;
import com.company.common.server.constant.IRelBusiType;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Authc
@RestController
@RequestMapping("/mgr/mall/orderReturn")
@Api(tags = "Shop_Mgr_退货退款管理")
public class OrderReturnMgrController {

	@Autowired
	private OrderReturnsService orderReturnsService;
	@Autowired
	private ShopAfterSaleReturnsService shopAfterSaleReturnsService;
	@Autowired
	private UserRemoteService userRemoteService;
	@Autowired
	private OrderLogService orderLogService;
	@Autowired
	private ShopOrderService shopOrderService;

	@PostMapping("/query")
	@SysLog("退货退款单查询")
	@ApiOperation(value = "退货退款单查询", response = OrderReturnsModel.class)
	public BaseResult query(@RequestBody OrderReturnMgrQuery4PageParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		if (YNEnum.YES.getCode().equals(params.getIsAgent())) {
			params.setCompanyNo(userInfo.getCompanyNo());
		} else {
			params.setMainCompanyNo(userInfo.getCompanyNo());
			params.setIsAgent(null);
		}

		IPage<OrderReturns> page = orderReturnsService.page(new Page<>(params.getPage(), params.getRows()),
				new QueryWrapper<OrderReturns>()
						.eq(StringUtils.hasText(params.getMainCompanyNo()), "main_company_no",
								params.getMainCompanyNo())
						.eq(StringUtils.hasText(params.getCompanyNo()), "company_no", params.getCompanyNo())
						.apply(StringUtils.hasText(params.getIsAgent()), "main_company_no <> company_no")
						.like(StringUtils.hasText(params.getSn()), "sn", params.getSn())
						.eq(CheckUtils.hasInt(params.getUserId()), "user_id", params.getUserId())
						.like(StringUtils.hasText(params.getSn()), "name", params.getSn())
						.eq(StringUtils.hasText(params.getState()), "state", params.getState())
						.orderByDesc("start_date"));

		if (page == null || CollectionUtils.isEmpty(page.getRecords())) {
			return BaseResult.ok();
		}

		Set<Integer> userids = new HashSet<Integer>();
		page.getRecords().forEach(item -> {
			userids.add(item.getUserId());
		});

		//todo
		BaseClientResult<Map<Integer, UserSimple>> userResp= userRemoteService.getUserMapByIds(userids);
		Map<Integer, UserSimple> userMap =BaseClientResult.getResultData(userResp);

		IPage<OrderReturnsModel> data = page.convert(new Function<OrderReturns, OrderReturnsModel>() {
			@Override
			public OrderReturnsModel apply(OrderReturns entity) {
				return ShopOrderConvertUtils.getOrderReturns(entity, userMap);
			}
		});

		return BaseResult.ok(data);
	}

	@GetMapping("/get")
	@SysLog("退货退款单明细")
	@ApiOperation(value = "退货退款单明细", response = OrderReturnsModel.class)
	public BaseResult get(@RequestParam("sn") String sn) {
		OrderReturns entity = orderReturnsService.getById(sn);
		if (entity == null) {
			throw new BusinessException(MallErrorEnum.Order_After_Not);
		}

		List<OrderLog> records = orderLogService.list(new QueryWrapper<OrderLog>()
				.eq("order_type", IRelBusiType.Order_Returns_ObjType).eq("sn", sn).orderByAsc("cdt"));

		Set<Integer> userIds = new HashSet<Integer>();
		userIds.add(entity.getUserId());
		if (!CollectionUtils.isEmpty(records)) {
			records.forEach(item -> {
				userIds.add(item.getCman());
			});
		}
		BaseClientResult<Map<Integer, UserSimple>> userResp=userRemoteService.getUserMapByIds(userIds);
		Map<Integer, UserSimple> userMap = BaseClientResult.getResultData(userResp);
		OrderReturnsModel data = ShopOrderConvertUtils.getOrderReturns(entity, records, userMap);
		OrderModel orderInfo=shopOrderService.getOrder(entity.getOrderSn(), entity.getOrderItemId(), false, true, false, false, false);
		data.setOrderInfo(orderInfo);
		return BaseResult.ok(data);
	}

	@PostMapping("/check")
	@ApiOperation(value = "退货退款单审核")
	@StaffLogc(title = "退货退款单审核", action = "退货退款单审核", actionAdo = "退货退款单")
	public BaseResult check(@RequestBody OrderReturnsCheckParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		shopAfterSaleReturnsService.check(params, userInfo);
		return BaseResult.ok();
	}

	@PostMapping("/receive")
	@ApiOperation(value = "退货退款单收货确认")
	@StaffLogc(title = "退货退款单收货确认", action = "退货退款单收货确认", actionAdo = "退货退款单")
	public BaseResult receive(@RequestBody OrderReturnsReceiveParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		shopAfterSaleReturnsService.receive(params, userInfo);
		return BaseResult.ok();
	}

	@PostMapping("/refund")
	@ApiOperation(value = "退货退款单退款")
	@StaffLogc(title = "退货退款单退款", action = "退货退款单退款", actionAdo = "退货退款单")
	public BaseResult refund(@RequestBody OrderReturnsRefundParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		shopAfterSaleReturnsService.refund(params, userInfo);
		return BaseResult.ok();
	}

}
